package com.warmguard.core.service;

import com.warmguard.core.domain.vo.CompletionRequest;
import com.warmguard.core.domain.vo.CompletionResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class OpenAIService {

    private final WebClient webClient;

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    public OpenAIService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("https://api.openai.com/v1").build();
    }

    public Mono<String> generateText(String prompt) {
        return webClient.post()
                .uri("/engines/davinci-codex/completions")
                .header("Authorization", "Bearer " + apiKey)
                .bodyValue(new CompletionRequest(prompt))
                .retrieve()
                .bodyToMono(CompletionResponse.class)
                .map(response -> response.getChoices().get(0).getText());
    }
}
